﻿using System.Windows.Forms;
using ReagentStore.ERM;
using ReagentStore.UTL;

namespace ReagentStore
{
	public partial class CatalogDialog : Form
	{
		private readonly PassParamsHandler<Catalog> _feedbackHandler;
		private readonly DialogParam<Catalog> _param;
		private FormValidator _formValidator;

		public CatalogDialog(DialogParam<Catalog> param, PassParamsHandler<Catalog> handler)
		{
			InitializeComponent();

			_feedbackHandler = handler;
			_param = param;
			InitializeControlsByParam();
			InitializeValidator();
		}

		private void InitializeControlsByParam()
		{
			Catalog catalog = _param.Parameter;
			switch (_param.ActionType)
			{
				case ActionTypes.Insert:
					Text = "添加分类";
					break;

				case ActionTypes.Update:
					Text = "更新分类";
					textName.Text = catalog.Name;
					break;

				case ActionTypes.Delete:
					Text = "删除分类";
					textName.Text = catalog.Name;
					groupBox.Enabled = false;
					break;
			}
		}

		private void InitializeValidator()
		{
			_formValidator = new FormValidator(errorProvider);
			_formValidator.Add(new RequiredValidator(textName, "请输入分类名称"));
		}

		private void Feedback()
		{
			switch (_param.ActionType)
			{
				case ActionTypes.Insert:
				case ActionTypes.Update:
					_param.Parameter.Name = textName.Text;
					break;
				case ActionTypes.Delete:
					break;
			}

			PassParamsHandler<Catalog> handler = _feedbackHandler;
			if (handler != null)
				handler(_param);
		}

		private void CatalogDialog_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (DialogResult != DialogResult.OK)
				return;

			if (!_formValidator.IsValid())
			{
				e.Cancel = true;
				return;
			}

			Feedback();
		}
	}
}